package com.zlc.workflow.utils;


import com.zlc.common.common.exception.WorkflowException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 流处理工具
 *
 * @author zhanglei
 */
public final class StreamHelper {

    /**
     * 将流转换成二进制
     *
     * @param stream  流
     * @return         二进制
     */
    public static byte[]  getByte(InputStream stream){
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];

            int num = stream.read(bytes);
            while(num != -1){
                outputStream.write(bytes,0,num);
                num = stream.read(bytes);
            }

            outputStream.flush();
            return outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw new WorkflowException(e.getMessage());
        }finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String getStr(InputStream stream){
        byte[] bytes = getByte(stream);
        return byteToStr(bytes);
    }

    public static String byteToStr(byte[] content){

        return new String(content, StandardCharsets.UTF_8);
    }

    public static InputStream strToStream(String context){
        new ByteArrayInputStream(context.getBytes(StandardCharsets.UTF_8));
        return null;
    }

}
